'''
同佑e生重大疾病保险产品计划
'''
import sys
sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import execjs
import requests
from common.helper import Helper



class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "同佑e生重大疾病保险产品计划"

    def genProductInfo(self):

        planA = {

            # 年龄段
            "year": [str(i) for i in range(0, 41)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["100000", "200000", "300000", "400000", "500000"],
            # 保险期间
            "expire": ["30年", "70岁", "终身"],
            # 缴费期间
            "interval": ["30年", "70岁"],
            # 缴费方式 1 年缴 12 月缴
            "payType": ["1", "12"],
            # 附加两全险 0 否 1 是
            "ext_item": ["0", "1"]
        }

        for v in product(planA["year"], planA["gender"], planA["money"], planA["expire"], planA["interval"],
                         planA["payType"], planA["ext_item"]):

            if v[3] == "30年" and v[4] == "70岁":
                continue

            if v[3] == "30年" and v[4] == "终身":
                continue

            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], v[5], v[6]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], v[5], v[6]
            ))

        planB = {

            # 年龄段
            "year": [str(i) for i in range(41, 46)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["100000", "200000"],
            # 保险期间
            "expire": ["70岁", "终身"],
            # 缴费方式 1 年缴 12 月缴
            "payType": ["1", "12"],
            # 附加两全险 0 否 1 是
            "ext_item": ["0", "1"]

        }

        for v in product(planB["year"], planB["gender"], planB["money"], planB["expire"],
                         planB["payType"], planA["ext_item"]):

            if v[3] == "70岁":

                interval = "70岁"

            else:

                interval = "30年"

            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], interval, v[4], v[5]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], interval, v[4], v[5]
            ))

        planC = {

            # 年龄段
            "year": [str(i) for i in range(46, 51)],
            # 性别
            "gender": ["M", "F"],
            # 保额
            "money": ["100000"],
            # 保险期间
            "expire": ["70岁"],
            # 缴费期间
            "interval": ["70岁"],
            # 缴费方式 1 年缴 12 月缴
            "payType": ["1", "12"],
            # 附加两全险 0 否 1 是
            "ext_item": ["0", "1"]

        }
        for v in product(planC["year"], planC["gender"], planC["money"], planC["expire"], planC["interval"],planC["payType"],
                         planC["ext_item"]):
            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], v[5], v[6]
            ))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(

                v[0], v[1], v[2], v[3], v[4], v[5], v[6]
            ))

    # 执行爬虫
    def requestJson(self,dt):

        js = open('./' + self.name + '.js', mode='r', encoding="utf-8").read()

        cxt = execjs.compile(js)

        # 保障期限
        if dt["expire"] == "30年":

            expire = "30"

        elif dt["expire"] == "70岁":

            expire = "70"
        else:
            expire = "105"

        if dt["interval"] == "30年":

            interval = 30
        else:

            interval = 70


        data = {

            "procode": "TCIB07",
            "mainAmount": dt["money"],
            "mainInsure": expire,
            "mainPayment": interval,
            "mainDurationUnit": 6,
            "mainPaytype": dt["payType"],
            "addition": "1" if dt["ext_item"] == "1" else "2" ,
            "additionAmount": dt["money"],
            "additionInsure": 80 if dt["expire"] == "终身" else expire,
            "additionDurationUnit": 6,
            "additionPayment": interval,
            "tbRelation": 0,
            "error": {
                "isRight": "null",
                "errorMsg": "保险期间30年仅限于30万至50万保额可投，请重新选择保险期间或保额"
            }
        }

        xs_insper = {

          "selfType": "ins",
          "currentType": 0,
          "birthday": "{year}-12-04".format(year = str(2019-int(dt["year"]))),
          "fullName": "",
          "age": int(dt["year"]),
          "maxJob": "",
          "smallJob": "",
          "job": "",
          "gender": "1" if dt["gender"] == "M" else "2",
          "idNo": "",
          "province": "110000",
          "city": "110100",
          "area": "110102",
          "email": "",
          "phone": "",
          "zipcode": "",
          "address": "",
          "occupation": "",
          "occupationCode": "",
          "occupationName": "",
          "occupationMediumCode": "",
          "occupationSmallCode": "",
          "error": {
            "isRight": "null",
            "errorid": "",
            "errorMsg": "投保人信息填写正确"
          }
        }

        try:
            result = cxt.call("calPremium",data,xs_insper)

            if result:

                price = Helper.decimalParse(result)

                data = {

                    "name":self.name,

                    "id":dt["id"],

                    "price":price
                }
                self.mysql.updatePrice( data )

            else:

                # 任务执行失败
                data = {
                    "name": self.name,
                    "id": dt["id"],
                    "state": 3
                }
                print("/*产品价格更新失败:%d*/"%dt["id"])
                self.mysql.updateTask(data)

        except :

            pass


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }

            self.mysql.updateTask(data)

            self.requestJson(dt)

